package org.cttic.visualization.visualization.util.trackQuery;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHost;
import org.cttic.visualization.visualization.common.T_mysqlData;
import org.cttic.visualization.visualization.common.module.provinceData;
import org.cttic.visualization.visualization.common.trackQueryData;
import org.cttic.visualization.visualization.util.ConvertColor;
import org.cttic.visualization.visualization.util.DateUtil;
import org.cttic.visualization.visualization.util.GpsCoordinateUtils;
import org.cttic.visualization.visualization.util.ParseJsonDataUtil;
import org.cttic.visualization.visualization.util.itineraryQuery.queryUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author shkstart
 * @create 2020-05-25 20:08
 */
@Component
public class trackQuery {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private queryUtil query;
    public void esQueryTravel(RestHighLevelClient esClient,String provinceId,String vehPlate,int vehPlateColor,String startTime,String endTime,List<trackQueryData.vehLocation> list){
        String province = provinceData.province.get(Integer.parseInt(provinceId));


        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 搜索方式
        // matchAllQuery搜索全部
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.termQuery("vehicle.keyword",vehPlate));
        boolQueryBuilder.must(QueryBuilders.termQuery("platecolor",vehPlateColor+""));
        boolQueryBuilder.must(QueryBuilders.rangeQuery("positiontime").gte(startTime).lte(endTime));
//        searchSourceBuilder.aggregation(AggregationBuilders.cardinality("qc_vehicleNo").field("vehiclePlate"));
        if(provinceId!=null&&!provinceId.contains("|")){
            System.out.println(Long.parseLong(provinceId)*10000);
            System.out.println(provinceId+9999);
            boolQueryBuilder.must(QueryBuilders.rangeQuery("curaccesscode").gte(Long.parseLong(provinceId)*10000+"").lte(provinceId+9999));
        }else if(provinceId!=null&&provinceId.contains("|")){
            String[] split = provinceId.split("\\|");
            for (int i=0;i<split.length;i++){
                boolQueryBuilder.must(QueryBuilders.rangeQuery("curaccesscode").gte(Long.parseLong(split[i])*10000+"").lte(split[i]+9999));
            }
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchSourceBuilder.sort("positiontime");
        searchSourceBuilder.size(5000);
        String provin = provinceData.province.get(Integer.parseInt(provinceId));
        String index = getEsIndex.esIndex.get(provin)+"-all";
        System.out.println("====查询index："+index+"====");
        // 执行搜索,向ES发起http请求
        SearchRequest Request = new SearchRequest(index);
        Request.types("_doc");
        Request.source(searchSourceBuilder);
        SearchResponse rp = null;
        try {

            rp = esClient.search(Request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("rp:"+rp);
        SearchHit[] hits = rp.getHits().getHits();
        for (SearchHit hit : hits) {
            trackQueryData.vehLocation vehLocation = new trackQueryData.vehLocation();
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            Object positiontime = sourceAsMap.get("positiontime");
            if(positiontime!=null){
                vehLocation.setTransTime(DateUtil.timeToT(String.valueOf(positiontime)));
            }
            Object speed = sourceAsMap.get("vec2");
            if(speed!=null){
                vehLocation.setVec(String.valueOf(speed));
            }
            Object direction = sourceAsMap.get("direction");
            if(direction!=null){
                vehLocation.setDir(String.valueOf(direction));
            }
            Object lat = sourceAsMap.get("lat");
            Object lon = sourceAsMap.get("lon");
            if(lat!=null&&lon!=null){
                double latString = Double.parseDouble(String.valueOf(lat))/1000000;
                double lonString = Double.parseDouble(String.valueOf(lon))/1000000;
                double lat1 = GpsCoordinateUtils.calWGS84toGCJ02Lat(latString, lonString);
                double log1 = GpsCoordinateUtils.calWGS84toGCJ02Log(latString, lonString);
                System.out.println(log1);
                vehLocation.setLat(lat1+"");
                vehLocation.setLng(log1+"");
            }
            list.add(vehLocation);
        }
    }

    public void trackQuery(String provinceId,String vehPlate,String vehPlateColor,String queryValue1,List<trackQueryData.vehLocation> list){

        System.out.println("********轨迹点查询按行程编号开始查询*********");

        SearchHit[] hits = query.queryByTravelId(vehPlate, vehPlateColor, queryValue1,provinceId);

        if(hits.length>0) {
            System.out.println("********轨迹点查询完成行程开始查询*********");
            pachking(hits,list);
            System.out.println("********轨迹点查询完成行程结束查询*********");
        }else {
            SearchHit[] hits2 = query.queryByTravelId2(vehPlate, vehPlateColor, queryValue1,provinceId);
            if(hits2.length>0){
                System.out.println("********轨迹点查询未完成行程开始查询*********");
                pachking(hits2,list);
                System.out.println("********轨迹点查询未完成行程结束查询*********");
            }
        }

    }
    public void trackQueryByTime(String provinceId,String vehPlate,String vehPlateColor,String startTime,String endTime,List<trackQueryData.vehLocation> list){
        SearchHit[] searchHits1 = query.queryByTansTimeBetween(vehPlate, vehPlateColor, startTime, endTime,provinceId);
        if(searchHits1.length>0){
            SearchHit hit = searchHits1[0];
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            Object travelId = sourceAsMap.get("travelId");
            if(travelId!=null){
                String value = String.valueOf(travelId);
                trackQuery(provinceId,vehPlate,vehPlateColor,value,list);
            }
        }else {
            SearchHit[] searchHits2 = query.queryByTansTimeBetween2(vehPlate, vehPlateColor, startTime, endTime,provinceId);
            if(searchHits2.length>0){
                SearchHit hit = searchHits2[0];
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                Object travelId = sourceAsMap.get("travelId");
                if(travelId!=null){
                    String value = String.valueOf(travelId);
                    trackQuery(provinceId,vehPlate,vehPlateColor,value,list);
                }
            }
        }
    }


    public void pachking(SearchHit[] hits,List<trackQueryData.vehLocation> list){
        for (SearchHit hit : hits) {

            trackQueryData.vehLocation vehLocation = new trackQueryData.vehLocation();
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            Object tansTime = sourceAsMap.get("tansTime");
            if(tansTime!=null){
                vehLocation.setTransTime(DateUtil.timeToT(String.valueOf(tansTime)));
            }
            Object speed = sourceAsMap.get("speed");
            if(speed!=null){
                vehLocation.setVec(String.valueOf(speed));
            }
            Object direction = sourceAsMap.get("direction");
            if(direction!=null){
                vehLocation.setDir(String.valueOf(direction));
            }
            Map<String,Double> point = (Map<String,Double>)sourceAsMap.get("point");

            if(point!=null){
                Double lon = point.get("lon");
                Double lat = point.get("lat");
                    vehLocation.setLat(lat+"");
                    vehLocation.setLng(lon+"");

            }

            Object gantryType = sourceAsMap.get("gantryType");
            Object gantryId = sourceAsMap.get("gantryId");
            if(gantryId!=null&&gantryType!=null){
                int pointType = Integer.parseInt(String.valueOf(gantryType));
                //门架 省界门架
                if (pointType==2) {
                    String sql = "SELECT gantryId,roadSectionId,tollIntervals FROM `T_GANTRY_MOUNTING` " +
                            "where  gantryId= '" + gantryId + "'";
//                        List<mysqlUtilData> mysqlData = jdbcTemplate.query(sql, new BeanPropertyRowMapper(T_mysqlData.class));
                    List<Map<String, Object>> maps1 = jdbcTemplate.queryForList(sql);
                    if(maps1!=null&&maps1.size()>0){
                        Map<String, Object> stringObjectMap = maps1.get(0);
                        String tollIntervals = stringObjectMap.get("tollIntervals").toString();

                        if(!tollIntervals.contains("|")){
                            String sql2 ="SELECT unitId,provinceId,unitLength FROM `T_CHARGING_UNIT` where  unitId= '"+tollIntervals+"'";
                            List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql2);
                            if(maps!=null&&maps.size()>0){
                                Map<String, Object> map = maps.get(0);
                                Object unitLength = map.get("unitLength");
                                double value = Double.parseDouble(String.valueOf(unitLength)) / 1000;//单位m 需转km
                                System.out.println("****************查询mysql里程数信息******************");
                                vehLocation.setDis(value+"");
                            }
                        }else {
                            Double BillAm=0.00D;
                            String[] split = tollIntervals.split("\\|");
                            for (String s : split) {
                                String sql3 ="SELECT unitId,provinceId,unitLength FROM `T_CHARGING_UNIT` where  unitId= '"+s+"'";
                                List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql3);
                                if(maps!=null&&maps.size()>0){
                                    Map<String, Object> map = maps.get(0);
                                    Object unitLength = map.get("unitLength");
                                    BillAm+=Double.parseDouble(String.valueOf(unitLength))/1000;//单位m 需转km
                                    System.out.println("****************查询mysql里程数信息******************");
                                }
                            }
                            vehLocation.setDis(BillAm+"");
                        }
                    }
                    //收费站
//                } else if (pointType == 1) {
//                    String sql = "SELECT stationId,gnclat,gnclng,stakeNum FROM `T_STATION` " +
//                            "where  stationId= '" +
//                            gantryId + "'";
//                    List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
//                    if(maps!=null&&maps.size()>0){
//                        Map<String, Object> stringObjectMap = maps.get(0);
//                        Object lat = stringObjectMap.get("gnclat");
//                        if(lat!=null){
////                            vehLocation.setLat(stringObjectMap.get("gnclat").toString());
//                        }
//                        Object lng = stringObjectMap.get("gnclng");
//                        if(lng!=null){
////                            vehLocation.setLng(stringObjectMap.get("gnclng").toString());
//                        }
//                        System.out.println("****************收费站查询mysql经纬度信息******************");
////                            String pileNumber = stringObjectMap.get("stakeNum") == null ? "": stringObjectMap.get("stakeNum").toString();
////                            identification.setPileNum(pileNumber);
////                        identification.setDirection(gantryId.substring(14, 15));
//                    }
                }
            }
            System.out.println(vehLocation.toString());
            list.add(vehLocation);
        }
    }

}














